package com.hmall.search.utils;

import cn.hutool.json.JSONUtil;
import com.hmall.api.dto.ItemDoc;
import com.hmall.search.config.EsProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

@Slf4j
@Component
public class EsUtil {

    private static final String DOC_INDEX_NAME = "items";

    private final EsProperties esProperties;

    @Getter
    private RestHighLevelClient client;

    public EsUtil(EsProperties esProperties) {
        this.esProperties = esProperties;
    }

    public String getUrl() {
        return "http://" + esProperties.getIp() + ":" + esProperties.getPort();
    }

    @PostConstruct
    public void init() {
        log.info("初始化 Elasticsearch 客户端，地址：{}", getUrl());
        client = new RestHighLevelClient(
                RestClient.builder(HttpHost.create(getUrl()))
        );
    }

    @PreDestroy
    public void close() {
        try {
            if (client != null) {
                client.close();
                log.info("Elasticsearch 客户端已关闭");
            }
        } catch (IOException e) {
            log.error("关闭 Elasticsearch 客户端失败", e);
        }
    }

    // 新增/修改文档
    public void addDoc(ItemDoc itemDoc) throws IOException {
        IndexRequest request = new IndexRequest(DOC_INDEX_NAME);
        request.id(itemDoc.getId());
        request.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
        log.info("添加/更新文档成功，ID：{}", itemDoc.getId());
    }

    // 删除文档
    public void deleteDoc(String itemId) throws IOException {
        DeleteRequest request = new DeleteRequest(DOC_INDEX_NAME, itemId);
        client.delete(request, RequestOptions.DEFAULT);
        log.info("删除文档成功，ID：{}", itemId);
    }

    // 查询文档
    public ItemDoc getDoc(String itemId) throws IOException {
        GetRequest request = new GetRequest(DOC_INDEX_NAME, itemId);
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        if (!response.isExists()) {
            log.warn("文档未找到，ID：{}", itemId);
            return null;
        }
        String json = response.getSourceAsString();
        return JSONUtil.toBean(json, ItemDoc.class);
    }
}
